package com.tianyi.fileUpload;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * 文件上传处理工具
 *
 * @author cuixuhui
 * @date 2020/05/08
 */
@Service
public class FileUploadService {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadService.class);

    //@Test
    //public void p(){
      //  System.out.println(getPhotoPath());
    //}

    public String getPhotoPath(){

        return System.getProperties().getProperty("user.home")+File.separator+"tianyi"+File.separator+"photo"+File.separator;
    }

    public String getTmpPhotoPath(){

        return getPhotoPath()+"tmp"+File.separator;
    }

    /**
     * 上传文件
     * @param file
     * @return      文件名
     */
    public String uploadPhotoWithThumbnails(MultipartFile file){

        if (file == null || file.isEmpty()){
            logger.info("file is null");
            return null;
        }
        UUID uuid = UUID.randomUUID();
        String originalFilename = file.getOriginalFilename();
        String uuidStr = uuid.toString();
        String substring = uuidStr.substring(0, 10);
        String timestampStr = "_"+System.currentTimeMillis();
        uuidStr = substring+timestampStr;
        String fileName = uuidStr + "_" + originalFilename;

        try {
            saveThumbnailsFile(file, fileName);
            saveSourceFile(file, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 保存原文件
     */
    public File saveSourceFile(MultipartFile file, String fileName) throws IOException {
        //原文件
        File dest = new File(getPhotoPath() + fileName);
        //判断文件父目录是否存在
        mkParentDir(dest);
        file.transferTo(dest);
        return dest;
    }

    public void mkParentDir(File file){
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
            mkParentDir(file.getParentFile());
        }
    }

    public void saveThumbnailsFile(MultipartFile file, String fileName) throws IOException {
        File dest = new File(getTmpPhotoPath()+fileName);
        //判断文件父目录是否存在
        mkParentDir(dest);
        InputStream inputStream = file.getInputStream();
        Thumbnails.Builder<? extends InputStream> of = Thumbnails.of(inputStream);
        of.size(200, 300).keepAspectRatio(false).toFile(getTmpPhotoPath()+fileName);
        if (Objects.isNull(inputStream)){
            return;
        }
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除原图 && 缩略图
     * @param fileName
     */
    public void deletePhotoWithThumbnails(String fileName){

        if (StringUtils.isBlank(fileName)){
            return;
        }
        try{
            deletePhoto(fileName);
            File tmpFile = new File(getTmpPhotoPath() + fileName);
            tmpFile.delete();
        }catch (Exception e){
            logger.info("deletePhotoWithThumbnails error={}, fileName={}", e.getMessage(), fileName);
        }
    }

    /**
     * 删除原图图片
     * @param fileName
     */
    public void deletePhoto(String fileName){

        File sourceFile = new File(getPhotoPath() + fileName);
        sourceFile.delete();
    }
}
